#include <iostream>
#include <unistd.h>
#include <vector>

class ThreadData
{
public:
    std::string name;
    int x;
    int y;
};

class ThreadReturn
{
public:
    int excutr()
    {
        ret = x + y;
        return ret;
    }

    std::string name;
    int x;
    int y;
    int ret;
};

std::string  PrintHex(const pthread_t& tid)
{
    char buff[128];
    snprintf(buff,sizeof(buff) , "%0xlh",(unsigned int)tid);
    return buff;
}


//分配虚拟地址,执行不同函数
void* threadrun(void * args)
{
    //pthread_detach(pthread_self());

    std::string name = static_cast<const char*>(args);
    while(true)
    {
        std::cout << name << " is running " << std::endl;
        sleep(3);
        break;

    }
    pthread_exit(args);
}

const int num = 10;

int main()
{
    std::vector<pthread_t> tids;
    for(int i = 0 ; i < num ; ++i)
    {
        pthread_t tid;
        char* name = new char[128];
        snprintf(name,128,"thread_%d",i+1);

        pthread_create(&tid,nullptr,threadrun,name);
        tids.emplace_back(tid);
    }

    //线程分离 
    for(auto tid : tids)
    {
        pthread_detach(tid);
    }

    
    for(auto tid : tids)
    {
        // pthread_cancel(tids[i]);
        
        void* result = nullptr;
        int n = pthread_join(tid,&result);
        std::cout << "name " << (long long int)result <<" quit " << " n " << n << std::endl;
        //delete (char*)result;
    }
    // pthread_t tid;
    // ThreadData* td = new ThreadData();

    // td->name = "thread_1";
    // td->x = 10;
    // td->y = 20;

    // //线程创建
    // pthread_create(&tid,nullptr,threadStart,(void*)td);
    
    // //线程等待 join
    // void* code = nullptr;
    // int n = pthread_join(tid,&code);
    // if(n == 0)
    // {
    //     std::cout << "main pthread wait success new thread exit code " << ((ThreadReturn*)code)->ret << std::endl;
    //     delete (ThreadReturn*)code;
    // }
    return 0;
}
